import dayjs from "dayjs"
import { random } from "@/uni_modules/uview-plus"
import graceRichText from "../config/rich-text-format.js"
import { chatApi } from '@/apis/cloud/chat'
import {
	extractHrefOrReplace,
	getScaledImageSize, 
	chooseFile, 
	fileTypeFormat, 
	fixImageSrc, 
	formatFileSize, 
	getTimeStringAutoShort, 
	setIcon, 
	processImageUrl, 
	getFileDetails, 
	saveUriToTempFile ,
} from "@/utils/chat"

const AvaterBaseUrl = "https://cloud.mfarmers.com/dist/interface/public/upload/avatar/";

export default {
  data() {
    return {
			winSize: {},
			currentMsg: {},
			popStyle: {
			},
			copyShow: false,
			startX: 0,
			startY: 0,
			moved: false,
    };
  },
	created() {
		this.getSetting();
	},
	mounted() {
		uni.getSystemInfo({
			success: (res) => {
				this.winSize = {
					witdh: res.windowWidth,
					height: res.windowHeight,
					percent: res.windowHeight - (res.windowHeight / 3)
				}
			}
		})
	},
  methods: {
		back () {
			uni.switchTab({
				url: '/pages/chat/list/index'
			})
		},
		setUserImg (phone) {
			return AvaterBaseUrl + phone + '.jpg'
		},
		setRecall (data) {
			const findIndex = this.talkList.findIndex(item => {
				return data.id == item.id
			})
			
			this.talkList[findIndex].status = 12;
		},
		async getSetting() {
			const params = {
				'data[account]': this.imInfo.account,
				'data[token]': this.userInfo.token,
				'data[myAccount]': this.imInfo.account,
				'data[item]': 'recall_time',
				url: 'index.php/users/system-settings/getSetting'
			}
			const msg = await chatApi(this.userInfo.token, params);
			if(msg.code == 200) {
				this.recall = +msg.data.value;
			}else {
				this.recall = 86400;
			}
		},
		formatTime(timeString) {
			if (!timeString) return '';
			return dayjs(timeString).format('YYYY-MM-DD HH:mm');
		},
		keyboardHeightChange (res) {
			this.$refs.inputBar.updateKeyboardHeightChange(res);
		},
		hidedKeyboard () {
			this.$refs.inputBar.hidedKeyboard();
		},
		keyboardUp () {
			// #ifdef H5
			this.$nextTick(() => {
				this.$refs.paging.scrollToBottom();
			})
			// #endif
		},
		async getQuoteContext (content, status, name) {
			let { type, content: txtContent } = content
			let html = '';
			if (status == '12') return '消息已被撤回';
			switch (type) {
				case 'text': html = `<div class="reply-html">${txtContent}</div>`; break;
				case 'file': html = `[文件] ${content.name}`; break;
				case 'dir': html = `[文件夹] ${content.name}`; break;
				case 'img/text': html = await this.setHtmlContent(txtContent); break;
				case 'img': html = `<img src='${processImageUrl(txtContent)}' style="max-width: 120px;"</img>`; break;
				default: html = '';
			}
			return html
		},
		getStatusText (status) {
			switch (status) {
				case 1: return '审批中';
				case 2: return '已通过';
				case 3: return '已拒绝';
				case 4: return '已撤销';
				default: return '';
			}
		},
		handleReedit (item) {
			const htmlString = item.content[0].content;
			const match = htmlString.match(/<p[^>]*>([\s\S]*?)<\/p>/i);
			if (match) {
				this.$refs.inputBar.msg = match[1];
			} else {
				this.$refs.inputBar.msg = htmlString; // 防止报错，兜底
			}
			this.focus = true;
		},
		copyCancel() {
			this.copyContent = '';
			this.copyShow = false;
			this.$refs.inputBar.copyCancel();
		},
		handleCopyShow (val) {
			this.copyContent = val;
			this.copyShow = true;
		},
		longpress(e, record) {
			if (this.moved) return
			this.currentMsg = record;
			this.popStyle = {};
			uni.createSelectorQuery()
			.select('#msg-' + record.id)
			.boundingClientRect(rect => {
					if (!rect) return;
					const { top, bottom } = rect;
					if(bottom > this.winSize.percent) {
						this.popStyle.top = `${top - 70}px`
					}else {
						this.popStyle.top = `${bottom + 7}px`
					}
					if(record.from_account == this.friend?.friend_account || record.from_account != this.imInfo?.account) {
						this.popStyle.left = `53px`
					}else {
						this.popStyle.right = `53px`
					}

					try{
					  uni.vibrate({}); // 震动提示
					}catch(err){}
					
					this.$refs.popoverMenu.show(this.popStyle);
			})
			.exec();
		},
		touchStart(e) {
			const touch = e.touches[0]
			this.startX = touch.pageX
			this.startY = touch.pageY
			this.moved = false
		},
		touchMove(e) {
			const touch = e.touches[0]
			if (Math.abs(touch.pageX - this.startX) > 10 ||
					Math.abs(touch.pageY - this.startY) > 10) {
				this.moved = true
			}
		},
		linkify (text) {
			if (!text) return "";
			const urlRegex = /(https?:\/\/[^\s]+)/g;
			return text.replace(urlRegex, function(url) {
					return `<a href="${url}" target="_blank" rel="noopener noreferrer">${url}</a>`;
			});
		},
		openDoc(message, detail, worker_id) {
			if(message.percentage && message.percentage < 100) {
				return
			}
			const type = ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pdf'];
			const str = detail.name.split('.');
			const icon = str[str.length - 1];
			const that = this;
			let url = ''
			const xtoken = this.nextCloud.xtoken
		
		  const fileName = encodeURIComponent(encodeURIComponent(detail.name)); // 双重编码
		  const fileurl = encodeURIComponent(detail.url); // 单次编码
		
		  if (type.includes(icon)) {
		    let previewUrl = '';
		    if (xtoken) {
		      previewUrl = `https://cloud.mfarmers.com/dist/previewDoc1.html?xtoken=${xtoken}&nc_id=${detail.nc_id ? detail.nc_id : ''}&fileName=${fileName}&type=mobile&user=${worker_id}&url=${fileurl}`;
		    } else {
		      previewUrl = `https://cloud.mfarmers.com/dist/previewDoc1.html?fileName=${fileName}&type=mobile&user=${worker_id}&url=${fileurl}`;
		    }
		
		    const encodedData = encodeURIComponent(JSON.stringify({ previewUrl }));
		    url = `/pages/chat/message/common/previewDoc?data=${encodedData}`;
		  } else {
		    url = `/pages/chat/message/common/downloadDoc?fileName=${fileName}&fileSize=${detail.formatSize}&url=${fileurl}`;
		  }
		
		  uni.navigateTo({ url });
		},
		extractImageSrc(html,newBase = 'https://chat.mfarmers.com:88/') {
			const srcs = [];
			html.replace(/<img[^>]+src=(["'])([^"']+)\1/g, (match, quote, src) => {
				let newSrc = src;
				if (/^https?:\/\//i.test(src)) {
					// 已有域名的，替换域名部分
					const pathIndex = src.indexOf('/', src.indexOf('//') + 2);
					const path = src.substring(pathIndex);
					newSrc = newBase.replace(/\/+$/, '') + path;
				} else {
					// 相对路径，直接加上 newBase
					newSrc = newBase.replace(/\/+$/, '') + '/' + src.replace(/^\/+/, '');
				}
				srcs.push(newSrc);
				return match;
			});
			return srcs;
		},
		// 使用 uni-app 的 base64ToPath 方法（需要HBuilderX 3.1.0+）
		base64ToTempPath (base64Data) {
			return new Promise((resolve, reject) => {
				uni.base64ToPath({
					base64: base64Data,
					success: (res) => {
						resolve(res.tempFilePath);
					},
					fail: (err) => {
						reject(err);
					}
				});
			});
		},
		async setHtmlContent(content) {
			const cache = fixImageSrc(content);
			// #ifdef APP-PLUS
			const srcList = this.extractImageSrc(cache);
			// 获取所有图片的宽高（按顺序）
			const sizeList = await Promise.all(srcList.map(async (src) => {
				try {
					// 如果是 base64 格式，先转换为临时路径
					if (src.startsWith('data:image')) {
						src = await this.base64ToTempPath(src);
					}
					const size = await getScaledImageSize(src);
					return size;
				} catch (error) {
					console.error('处理图片失败:', error);
					return { width: 0, height: 0 }; // 返回默认尺寸
				}
			}));
		
			let index = 0;
			// 按顺序替换 <img> 标签
			const newHtml = cache.replace(/<img[^>]*>/g, (imgTag) => {
				const { width, height } = sizeList[index++] || {};
				// 只给没有宽高的图片添加宽高属性
				if (!imgTag.includes('width=') && width && height) {
					return imgTag
							.replace(/ onclick="[^"]*"/g, '')   // 去掉 onclick
							.replace(/>$/, ` width="${width}" height="${height}">`); // 添加宽高
				}
				return imgTag.replace(/ onclick="[^"]*"/g, '').replace(/http:/g, 'https:').replace(/:81/g, ':88');
			});
		
			return newHtml;
			// #endif
		
			// #ifdef H5
			return graceRichText.format(cache).replace(/http:/g, 'https:').replace(/:81/g, ':88');
			// #endif
		},
		// 处理信息中图片链接
		async setImgUrl (content) {
			if (this.isRichText(content)) {
				return graceRichText.format(content);
			} else {
				const result = await getScaledImageSize(processImageUrl(content));
		
				return {
					url: processImageUrl(content),
					width: result?.width ? result.width : 100,
					height: result?.height ? result.height : 100,
				}
			}
		},
		// 判断是否富文本
		isRichText (str) {
			return /<[a-z][\s\S]*>/i.test(str);
		},
		// 文件图标处理
		setFileIcon (fileName) {
			const str = fileName.split('.');
			return fileTypeFormat(str[str.length - 1])
		},
		// 相隔时间是否大于10分钟
		showTimestamp(index) {
			if(!this.talkList[index].send_time || (!this.talkList[index-1] || !this.talkList[index-1].send_time)) {
				return false
			}
			if(index === this.talkList.length-1) {
				return false
			}
			const current = new Date(this.talkList[index].send_time).getTime();
			const prev = new Date(this.talkList[index+1].send_time).getTime();
			const timestamp = current - prev;
			if(timestamp > 30*60*1000) {
				return true
			}else {
				return false
			}
		},
		// 计算时间差
		setTimestamp(index) {
			const current = this.talkList[index];
			const prev = this.talkList[index+1];
			const result = getTimeStringAutoShort(new Date(current.send_time).getTime(), true)
		
			return result
		},
		setProgress (uuid, progress) {
			const find = this.talkList.find(item => {
				return uuid && item?.uuid && item?.uuid === uuid
			})
		
			if (find) {
				find.percentage = progress;
			}
			return find
		},
		handleUploadCallback(e) {
			const find = this.setProgress(e.data.uuid, e.data.progress);
			// success 发送消息
			if (e.type == 'success') {
				if (e.data[0].response.data.startsWith("http://chat.mfarmers.com:81")) {
					e.data[0].response.data = e.data[0].response.data.replace("http://chat.mfarmers.com:81/", "https://chat.mfarmers.com:88/");
				}
				const sendMsg = this.talkList.find(item => {
					return item?.uuid === e.data.uuid
				})
				sendMsg.content[0].url = e.data[0].response.data;
				sendMsg.fid = e.data[0].response.id;
				this.sendMessage(e.data[0].response.data, 'file', e.data[0], sendMsg);
			}
		},
		// 选择文件
		async chooseFile () {
			const _self = this;
			// #ifdef APP-PLUS
			this.$refs.XeUpload.upload('file');
			// #endif
			// #ifdef H5
			uni.chooseFile({
				count: 1,
				success (res) {
					if (res.tempFiles[0].size > (1024 * 1024 * 50)) {
						uni.showToast({
							icon: 'none',
							duration: 2500,
							title: '请选择小于50MB的文件'
						})
						return
					}
		
					const fileInfo = {
						size: res.tempFiles[0].size,
						name: res.tempFiles[0].name,
					}
					_self.uploadImgOrFile(res.tempFilePaths[0], fileInfo);
				},
				fail (err) {
					console.log(err)
				}
			})
			// #endif
		},
		isValidJSON (jsonString) {
			try {
				JSON.parse(jsonString);
				return true;
			} catch (e) {
				return false;
			}
		},
		checkContent (content) {
			if (this.isValidJSON(content)) {
				return JSON.parse(content);
			} else {
				return [];
			}
		},
		// 名称超长处理
		showUserName (username) {
			if (username && username.length > 2) {
				return username.substr(1, 2);
			} else {
				return username;
			}
		},
  },
};
